﻿//  --------------------------------
//  Copyright (c) Microsoft Corporation. All rights reserved.
//  This source code is made available under the terms of the Microsoft Public License (Ms-PL)
//  http://www.codeplex.com/oxite/license
//  ---------------------------------
using System.Web.Mvc;
using System.Linq;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using Oxite.Extensions;
using Oxite.Infrastructure;
using Oxite.Models;
//using ECube.SEC.FormsAuthentication.Extensions;
//using ECube.SEC.FormsAuthentication.Models;
//using ECube.SEC.FormsAuthentication.Services;
//using ECube.SEC.Membership.Models;
//using ECube.SEC.Membership.Services;
using Oxite.Services;
using Oxite.ViewModels;
using ECube.SEC.Models;
using ECube.SEC.Services;
namespace ECube.SEC.Controllers
{
    public class ADUserController : Controller
    {
        //private  IADAuthenticationUserService adAuthenticationUserService;
        //private readonly IUserService userService;
        //private readonly IFormsAuthenticationUserService faUserService;

        public ADUserController()
        {
                        
        }

        public  ActionResult Item(ADConnect connect)
        {
            if (connect == null)
            {
                connect = new ADConnect() { Key = "local", ContextType = ContextType.Domain };
            }

            return this.PartialView("User/ADUsers", connect);
        }
        public  JsonResult Find(ADConnect connect)
        {
            if (connect == null)
            {
                connect = new ADConnect() { Key="local", ContextType= ContextType.Domain };
            }
            IADAuthenticationUserService adAuthenticationUserService = ADAuthenticationUserService.GetInstance(connect);
            IEnumerable<UserPrincipal> us = adAuthenticationUserService.FindUsers(null);
            if (us != null)
            {
               
                var result = new
                {
                    aaData = us.Select(up => 
                        new string[]{up.SamAccountName,up.DisplayName ?? "",up.EmailAddress ?? "" ,up.Description ?? ""}
                        ).ToArray()
                };
                //var result = new { aaData = us.Select(up => new ADUser() { DisplayName = up.DisplayName,
                //                                                          AccountExpirationDate = up.AccountExpirationDate,
                //                                                          AllowReversiblePasswordEncryption = up.AllowReversiblePasswordEncryption,
                //                                                          AccountLockoutTime =up.AccountLockoutTime,
                //                                                          BadLogonCount= up.BadLogonCount,
                //                                                          DelegationPermitted = up.DelegationPermitted,
                //                                                          Description = up.Description,
                //                                                          DistinguishedName = up.DistinguishedName,
                //                                                          EmailAddress = up.EmailAddress,
                //                                                          EmployeeId = up.EmployeeId,
                //                                                          Enabled = up.Enabled,
                //                                                          GivenName = up.GivenName,
                //                                                          Guid = up.Guid,
                //                                                          HomeDirectory = up.HomeDirectory,
                //                                                          HomeDrive = up.HomeDrive,
                //                                                          LastBadPasswordAttempt = up.LastBadPasswordAttempt,
                //                                                          LastLogon = up.LastLogon,
                //                                                          LastPasswordSet = up.LastPasswordSet,
                //                                                          MiddleName = up.MiddleName,
                //                                                          Name = up.Name,
                //                                                          PasswordNeverExpires = up.PasswordNeverExpires,
                //                                                          PasswordNotRequired = up.PasswordNotRequired,
                //                                                          PermittedLogonTimes = up.PermittedLogonTimes,
                //                                                          SamAccountName = up.SamAccountName,
                //                                                          ScriptPath = up.ScriptPath,
                //                                                          SmartcardLogonRequired = up.SmartcardLogonRequired,
                //                                                          StructuralObjectClass = up.StructuralObjectClass,
                //                                                          Surname = up.Surname,
                //                                                          UserCannotChangePassword = up.UserCannotChangePassword,
                //                                                          UserPrincipalName = up.UserPrincipalName,
                //                                                          VoiceTelephoneNumber = up.VoiceTelephoneNumber
                //                                                        }
                //                                    ).ToArray() 
                //                 };
                return Json(result);
            }
            return null;
        }

        //public OxiteViewModel SignIn()
        //{
        //    return new OxiteViewModel { Container = new SignInPageContainer() };
        //}

        //[HttpPost]
        //public object SignIn(UserLogin login, string returnUrl)
        //{
            
        //        //TODO: (erikpo) Move the following validation logic into a validator

        //        //if (string.IsNullOrEmpty(username))
        //        //    ModelState.AddModelError("username", "You must specify a username.");

        //        //if (string.IsNullOrEmpty(password))
        //        //    ModelState.AddModelError("password", "You must specify a password.");

        //        if (ModelState.IsValid)
        //        {
        //            if (userService.SignIn(() => userService.GetUser(login.Username,login.Password,login.LoginDomain), 
        //                (u) => formsAuthentication.SetAuthCookie(u.Name, login.RememberMe)))
        //            {
        //                if (!string.IsNullOrEmpty(returnUrl) && returnUrl.StartsWith("/"))
        //                    return Redirect(returnUrl);

        //                return Redirect(Url.AppPath(Url.Home()));
        //            }

        //            ModelState.AddModelError("_FORM", "输入的用户名或密码不正确！");
        //        }
           
        //    return SignIn();
        //}

        //public ActionResult SignOut()
        //{
        //    formsAuthentication.SignOut();

        //    userService.SignOut();

        //    return Redirect(Url.AppPath(Url.Home()));
        //}

        //public OxiteViewModelItem<UserInput> Registration()
        //{
        //    return new OxiteViewModelItem<UserInput>(null);
        //}
        //[HttpPost]
        //public OxiteViewModelItem<UserInput> Registration(UserInput input)
        //{
        //    return new OxiteViewModelItem<UserInput>(input);
        //}

        //[HttpGet]
        //public OxiteViewModelItem<User> ChangePassword(User user)
        //{
        //    if (user == null) return null;

        //    //TODO: (erikpo) Check permissions or let the current user change their password

        //    return new OxiteViewModelItem<User>(user);
        //}

        //[ActionName("ChangePassword"), HttpPost]
        //public object ChangePasswordSave(User user, UserChangePasswordInput userInput)
        //{
        //    if (user == null) return null;

        //    //TODO: (erikpo) Check permissions

        //    if (ModelState.IsValid)
        //    {
        //        ModelResult results = faUserService.ChangePassword(user, userInput);

        //        if (!results.IsValid)
        //        {
        //            ModelState.AddModelErrors(results.ValidationState);

        //            return ChangePassword(user);
        //        }
            
        //        return Redirect(Url.AppPath(Url.ManageUsers()));
        //    }
        //    return new OxiteViewModelItem<User>(user);
        //}
    }
}
